package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;

/**
 * @author xushun
 * @email 505232797@qq.com
 * @date 2019/2/19 17:53
 */
@RestController
public class QueryController {

    @Value("${export.rootDir}")
    String rootDir;

    @Autowired
    JdbcTemplate jdbcTemplate;

    @GetMapping("query")
    public String query(String sql) throws Exception {
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        if (maps != null && !maps.isEmpty()) {
            String filePath = rootDir + "/" + System.currentTimeMillis() + ".csv";
            FileWriter fw = new FileWriter(filePath);
            BufferedWriter bw = new BufferedWriter(fw);
            boolean title = false;
            for (Map map : maps) {
                if (!title) {
                    bw.append(String.join(",", map.keySet()));
                    bw.newLine();
                    title = true;
                }
                bw.append(JSON.toJSONString(map.values()).replaceAll("\\[", "").replaceAll("\\]", ""));
                bw.newLine();
            }
            bw.flush();
            bw.close();
            return filePath;
        }

        return "No data found";
    }

}
